var express = require('express');
var router = express.Router();
var shell=require('shelljs')
var devices = require("../model/devices");
var exportflag = require("../model/exportflag");

function randomString(len) {
    len = len || 32;
    const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    const maxPos = $chars.length;
    let pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});
router.get('/mobileconfig', function(req, res, next) {
    res.attachment();
    res.attachment('/udid.mobileconfig');

});
router.get('/ipa',function(req,res,net){
    //console.log('udid:'+req.query.udid+'random:'+randomString(10))
     var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth();
        var day=date.getDate();
        var hour=date.getHours();
        var minute=date.getMinutes();
        let name =year.toString()+month.toString()+day.toString()+hour.toString()+minute.toString()// randomString(10);
    console.log(shell.exec("fastlane adddevice username:'"+name+"' udid:'"+req.query.udid+"'"))
    const newObj = new devices();

    let udid = req.query.udid;
    newObj.name=name;
    newObj.udid=udid
    let findparams={
        udid:udid
    }
    if(udid){
        devices.find(findparams, (err,results)=> {
            if(err){
                res.render('download',{title:'download'});
            }else {
                if(results.length>0){
                    res.render('download',{title:'download'});
                }else{
                    newObj.save( (err, result)=>{
                        if(err){
                            res.render('download',{title:'download'});
                        }else{
                            exportflag.findOneAndUpdate({name:"flag"},{$set:{flag:"true"}},function (err,result) {
                                if(err){
                                    console.log('update flag failed')
                                }else{
                                    console.log('update flag success')
                                }
                            })
                            res.render('download',{title:'download'});
                        }
                    })
                }
            }
        })
    }
    else
    {
        res.render('download',{title:'download'});
    }

})
module.exports = router;
